package com.framework.plugin.xmlsql;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import org.apache.commons.lang.StringUtils;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.IPlugin;

@SuppressWarnings("rawtypes")
public class XmlSqlPlugin implements IPlugin {
	
	public static Map<String, String> sqlMap = new HashMap<>();
	
	private String[] packages;
	
	public XmlSqlPlugin() {
		packages = new String[]{"sql"};
	}
	
	public XmlSqlPlugin(String...packages) {
		this.packages = packages;
	}

	public String[] getPackages() {
		return packages;
	}

	public void setPackages(String[] packages) {
		this.packages = packages;
	}

	@Override
	public boolean start() {
		String classPath = PathKit.getRootClassPath();
		for(String p:packages) {
			String dir = classPath+"/"+p;
			File file = new File(dir);
			if(file.exists()) {
				File[] files = file.listFiles();
				for(File f:files) {
					String fname = f.getName();
					if(fname.endsWith(".sql.xml")) {
						try {
							String prefix = fname.substring(0, fname.length()-8)+".";
							XMLInputFactory factory = XMLInputFactory.newInstance();  
							InputStream is = new FileInputStream(f);
//							XMLStreamReader reader = factory.createXMLStreamReader(is);
							XMLEventReader reader = factory.createXMLEventReader(is);  
					        String lastSql = null;
					        while(reader.hasNext()) {  
					            XMLEvent event = reader.nextEvent();  
					            if(event.isStartElement()) {
					            	StartElement se = event.asStartElement(); 
					            	String name = se.getName().toString();
					                if(name.equals("sql")) {
						                String attr = se.getAttributeByName(new QName("id")).getValue();
						                lastSql = prefix+attr;
						                sqlMap.put(lastSql, "<sql>");
					                } else if(!name.equals("sqls")) {
					                	String txt = "<"+name;
					                	Iterator iter = se.getAttributes();
					                	while(iter.hasNext()) {
					                		Attribute attr = (Attribute)iter.next();
					                		System.err.println(attr.getName()+","+attr.getValue());
					                		txt+=" "+attr.getName()+"=\""+attr.getValue()+"\"";
					                	}
					                	txt+=">";
					                	sqlMap.put(lastSql, sqlMap.get(lastSql)+txt);
					                }
					            } else if(event.isCharacters()) {
					            	String text = event.asCharacters().getData();
					            	if(StringUtils.isNotBlank(text)) {
					            		sqlMap.put(lastSql, sqlMap.get(lastSql)+" "+StringUtils.trimToEmpty(text)+" ");
					            	}
					            } else if(event.isEndElement()) {
					            	String name = event.asEndElement().getName().toString();
					            	if(name.equals("sql")) {
					            		sqlMap.put(lastSql, sqlMap.get(lastSql)+"</sql>");
					            	} else if(!name.equals("sqls")) {
					            		sqlMap.put(lastSql, sqlMap.get(lastSql)+"</"+name+">");
					                }
					            }
					        } 
					        System.out.println(sqlMap);
					        is.close();  
						} catch (Exception e) {
							e.printStackTrace();
							throw new RuntimeException(e);
						}
					}
				}
			}
		}
		return true;
	}

	@Override
	public boolean stop() {
		return false;
	}

}
